<template>
  <div class="consultation-create-view">
    <div class="page-header">
      <el-button @click="router.back()" class="back-btn">
        <el-icon><ArrowLeft /></el-icon>返回
      </el-button>
      <h1 class="page-title">新建法律咨询</h1>
      <p class="page-subtitle">请详细描述您的法律问题，我们将为您匹配合适的律师</p>
    </div>

    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <span>咨询信息</span>
        </div>
      </template>

      <el-form
        :model="consultationForm"
        :rules="consultationRules"
        ref="consultationFormRef"
        label-width="120px"
        class="consultation-form"
      >
        <el-form-item label="咨询标题" prop="title">
          <el-input
            v-model="consultationForm.title"
            placeholder="请简要概括您的法律问题"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="咨询类型" prop="category">
          <el-select
            v-model="consultationForm.category"
            placeholder="请选择咨询类型"
            style="width: 100%"
          >
            <el-option label="婚姻家庭" value="婚姻家庭" />
            <el-option label="劳动争议" value="劳动争议" />
            <el-option label="合同纠纷" value="合同纠纷" />
            <el-option label="侵权责任" value="侵权责任" />
            <el-option label="刑事案件" value="刑事案件" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>

        <el-form-item label="问题描述" prop="description">
          <el-input
            v-model="consultationForm.description"
            type="textarea"
            :rows="8"
            placeholder="请详细描述您的法律问题，包括时间、地点、人物、事件经过等关键信息..."
            maxlength="2000"
            show-word-limit
            resize="none"
          />
        </el-form-item>

        <el-form-item label="预约时间" prop="scheduledTime">
          <el-date-picker
            v-model="consultationForm.scheduledTime"
            type="datetime"
            placeholder="选择预约时间（可选）"
            style="width: 100%"
            :disabled-date="disabledDate"
            :shortcuts="shortcuts"
          />
          <div class="time-tip">如不选择，将立即创建咨询并等待律师接单</div>
        </el-form-item>

        <el-form-item>
          <div class="form-actions">
            <el-button @click="router.back()">取消</el-button>
            <el-button type="primary" @click="submitForm" :loading="submitting">
              {{ submitting ? '提交中...' : '提交咨询' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, inject } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { userInfoStore } from '@/stores/userinfo'

const router = useRouter()
const api = inject('$api')
const userStore = userInfoStore()

const consultationFormRef = ref()
const submitting = ref(false)

const consultationForm = ref({
  title: '',
  category: '',
  description: '',
  scheduledTime: null,
})

const consultationRules = {
  title: [
    { required: true, message: '请输入咨询标题', trigger: 'blur' },
    { min: 5, max: 100, message: '标题长度在 5 到 100 个字符', trigger: 'blur' },
  ],
  category: [{ required: true, message: '请选择咨询类型', trigger: 'change' }],
  description: [
    { required: true, message: '请输入问题描述', trigger: 'blur' },
    { min: 20, message: '问题描述至少需要 20 个字符', trigger: 'blur' },
  ],
}

// 禁用今天之前的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}

const shortcuts = [
  {
    text: '1小时后',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() + 3600 * 1000)
      return date
    },
  },
  {
    text: '明天此时',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() + 3600 * 1000 * 24)
      return date
    },
  },
  {
    text: '3天后',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() + 3600 * 1000 * 24 * 3)
      return date
    },
  },
]

const submitForm = async () => {
  if (!consultationFormRef.value) return

  try {
    const valid = await consultationFormRef.value.validate()
    if (!valid) return

    submitting.value = true

    // 构建提交数据
    const submitData = {
      title: consultationForm.value.title,
      category: consultationForm.value.category,
      description: consultationForm.value.description,
      clientId: userStore.user?.id,
      scheduledTime: consultationForm.value.scheduledTime,
    }

    const response = await api.consultation.createConsultation(submitData)

    if (response.code === 200) {
      ElMessage.success('咨询创建成功！')
      // 跳转到咨询详情页面
      router.push(`/consultation/${response.data.id}`)
    } else {
      ElMessage.error(response.message || '创建咨询失败')
    }
  } catch (error) {
    if (error.fields) {
      // 验证错误，不显示错误消息
      return
    }
    console.error('创建咨询失败:', error)
    ElMessage.error('网络错误，请稍后重试')
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.consultation-create-view {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.back-btn {
  margin-bottom: 20px;
}

.page-title {
  font-size: 1.8rem;
  color: #1a3a5f;
  margin: 0 0 10px 0;
}

.page-subtitle {
  color: #666;
  margin: 0;
  font-size: 1rem;
}

.form-card {
  margin-top: 20px;
}

.card-header {
  font-size: 1.2rem;
  font-weight: bold;
  color: #1a3a5f;
}

.consultation-form {
  max-width: 600px;
  margin: 0 auto;
}

.time-tip {
  font-size: 0.8rem;
  color: #999;
  margin-top: 5px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

.form-actions .el-button {
  min-width: 120px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .consultation-create-view {
    padding: 10px;
  }

  .consultation-form {
    max-width: 100%;
  }

  .form-actions {
    flex-direction: column;
    gap: 10px;
  }

  .form-actions .el-button {
    width: 100%;
  }
}
</style>
